#人脸识别
import time
import numpy as np
import face_recognition as fr
import os
import threading
import global_variable as gl
import warnings
warnings.filterwarnings("ignore", message="Creating an ndarray from ragged...")
gl.face_queue_init()
# FaceImage = gl.get_hand_image()
# FaceName = gl.get_face_name()
gl.flag_init()

Encodings = []#人脸编码
ImageToNames = [] #人脸对应名字

def ReadJPG(imagepath): #对数据集进行编码
    imgnames = os.listdir(imagepath)
    for imgname in imgnames:
        # 读取图片
        image = fr.load_image_file(imagepath + "/" + imgname)
        image_encoding = fr.face_encodings(image)[0]
        Encodings.append(image_encoding)
        imgname = os.path.splitext(imgname)[0]
        ImageToNames.append(imgname)
    print("data read success")
    # print(ImageToNames)
    # print(Encodings)
# face_recognition 识别
# FaceImage = Queue(2) #传输人脸图像
# FaceName = Queue(1)

class FaceThread(threading.Thread):
    def __init__(self,ThreadID):
        threading.Thread.__init__(self)
        self.ThradID = ThreadID
    def run(self):
        print("线程id: ",self.ThradID)
        print("人脸识别")
        #name = "Unknow"
        name = 0
        while gl.get_flag():
            if not gl.get_face_image().empty():
                # print("into face while")
                image = gl.pop_face_image()
                unknown_encoding = fr.face_encodings(image)
                if len(unknown_encoding) > 0:
                    unknown_encoding = unknown_encoding[0]
                    results = fr.compare_faces(Encodings, unknown_encoding, tolerance=0.45)
                    distances = (fr.face_distance(Encodings, unknown_encoding))
                    min_distance_index = np.argmin(distances)
                    if results[min_distance_index]:
                        #name = str(min_distance_index) +":"+ ImageToNames[min_distance_index]
                        name = min_distance_index
                    if not gl.get_face_name().full():
                        gl.put_face_name(name)
                #print(name)
                time.sleep(2)
                gl.pop_face_image()
